package com.hl.wechat.demo.websocket;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.EncodeException;
import javax.websocket.Session;
import java.io.IOException;
import java.util.List;
import java.util.function.Consumer;
@Component
public class MessageSenderImpl implements IMessageSender {
    private Logger logger = LoggerFactory.getLogger(MessageSenderImpl.class);

    @Override
    public boolean sendMessage(Session session, Object msg) {
        try {
            logger.info("发送{}",JSON.toJSONString(msg));
            session.getBasicRemote().sendText(JSON.toJSONString(msg));
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public void broadcastMessage(List<Session> sessionList, Object msg) {
        sessionList.forEach(session -> {
            try {
                session.getBasicRemote().sendText(JSON.toJSONString(msg));
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }
}
